﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tamir.SharpSsh;
using System.Collections;
using System.Windows.Forms;

namespace GeoSwarm_Editor
{
    class SSH
    {

        private StatusDialog statusDialog;
        private string iP = string.Empty;
        private string password = string.Empty;
        private Sftp sftp;

        public SSH(StatusDialog statusDialog)
        {
            this.statusDialog = statusDialog;
        }

        public void Connect()
        {
            if (iP == string.Empty || password == string.Empty)
                throw new Exception("IP or password was not specified.");
            sftp = new Sftp(iP, "root", password);
            sftp.Connect(22);
            sftp.OnTransferProgress += new FileTransferEvent(sftp_OnTransferProgress);
            if (!sftp.Connected)
                throw new Exception("Could not connect. Check that your device is connected and that OpenSSH is enabled.");
        }

        public void Disconnect()
        {
            try
            {
                if (sftp.Connected)
                    sftp.Close();
            }
            catch (Exception) { };
        }

        public ArrayList ListDir(string dir)
        {
            if (sftp.Connected)
                return sftp.GetFileList(dir);
            else throw new Exception("There was no connection or the connection was lost.");
        }

        public void Transfer(string srcPath, string destPath)
        {
            if (sftp.Connected)
                sftp.Put(srcPath, destPath);
            else throw new Exception("There was no connection or the connection was lost.");
        }

        private void sftp_OnTransferProgress(string src, string dst, int transferredBytes, int totalBytes, string message)
        {
            if (this.statusDialog != null)
            {
                double percent = ((double)transferredBytes / (double)totalBytes) * 100;
                statusDialog.UpdatePercentDone((int)percent);
            }
        }

        #region Properties

        public string IP
        {
            get
            {
                return iP;
            }
            set
            {
                iP = value;
            }
        }

        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                password = value;
            }
        }

        #endregion
    }
}
